package ui.fragment.minefragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;

import com.linchaolong.android.imagepicker.ImagePicker;
import com.linchaolong.android.imagepicker.cropper.CropImage;
import com.linchaolong.android.imagepicker.cropper.CropImageView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.GridImageAdapter;
import adapter.GvAdapter;
import base.BaseBean;
import base.fragment.BaseNetFragment;
import student.andlei.com.student.R;
import ui.activity.DoTheWorkActivity;
import utils.NetUtils;
import utils.QiniuUploadUtils;
import utils.SPUtils;
/**
 * 意见反馈
 */
public class FeedbackFragment extends BaseNetFragment{
    private EditText ed;
    private RecyclerView gv;
    private Button bt;
    private GridImageAdapter adapter;
    public static Fragment getInstance() {
        return new FeedbackFragment();
    }
    @Override
    public void success(String action, BaseBean baseBean) {
        hideLoadDialog();
        if(baseBean.code == 200){
            selectList.clear();
            adapter.notifyDataSetChanged();
            ed.setText("");
        }
        toast(baseBean.msg);
    }

    @Override
    public void error(String action, Throwable e) {
        hideLoadDialog();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_feedback;
    }

    @Override
    protected void findViews() {
        ed = getView(R.id.ed_feedback_input);
        gv = getView(R.id.grid_view);
        bt = getView(R.id.bt_feedback_complete);
    }

    @Override
    protected void formatViews() {
        bt.setOnClickListener(this);
        initImagePicker();
//        imagePicker = new ImagePicker();
//        // 设置标题
//        imagePicker.setTitle("添加照片");
//        // 设置是否裁剪图片
//        imagePicker.setCropImage(false);
//        list = new ArrayList<>();
//        adapter = new GvAdapter(this.getActivity(), list);
//        gv.setAdapter(adapter);
//        gv.setOnItemClickListener(new AdapterView
//                .OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View
//                    view, int position, long id) {
//                //判断是否是最后一个。
//                if (position==parent.getChildCount()-1){
//                    if (position==3){//不能点击了
//
//                    }else{
//                        opnePhoto();
//                    }
//                }else{//可以加点预览功能。
//
//                }
//            }
//        });
    }
    private void initImagePicker() {
        GridLayoutManager manager = new GridLayoutManager(context, 6, GridLayoutManager.VERTICAL, false);
        gv.setLayoutManager(manager);
        adapter = new GridImageAdapter(context, onAddPicClickListener,false);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        adapter.UpdateImageResource(R.mipmap.add_img);
        gv.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() <= 0) {
                    return;
                }
                LocalMedia media = selectList.get(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片
                        PictureSelector.create(FeedbackFragment.this).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList);
                        break;
                }
            }
        });
    }
    private List<LocalMedia> selectList = new ArrayList<>();
    private int maxSelectNum = 3;
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            // 进入相册 不需要的api可以不写
            PictureSelector.create(FeedbackFragment.this)
                    .openGallery(PictureMimeType.ofImage())
                    .theme(R.style.picture_default_style)
                    .maxSelectNum(maxSelectNum)
                    .minSelectNum(1)
                    .selectionMode(PictureConfig.MULTIPLE)
                    .previewImage(true)
                    .isCamera(true)
                    .enableCrop(false)
                    .compress(true)
                    .glideOverride(160, 160)
                    .previewEggs(true)
                    .withAspectRatio(1, 1)
                    .hideBottomControls(false)
                    .isGif(true)
                    .freeStyleCropEnabled(false)
                    .circleDimmedLayer(false)
                    .showCropFrame(false)
                    .showCropGrid(false)
                    .openClickSound(false)
                    .selectionMedia(selectList)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    };
    @Override
    protected void formatData() {

    }

    @Override
    protected void getBundle() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_feedback_complete:
                if(ed.getText().toString().trim().length()<5){toast("意见反馈不能少于5个字！");return;}
                if(selectList.size()>0){
                    showLoadDialog();
                    final String yuming = SPUtils.getInstance(getActivity()).getString("domain");
                    List<String> list = new ArrayList<>();
                    for (int i = 0; i < selectList.size(); i++) {
                        list.add(selectList.get(i).getCompressPath());
                    }
                    QiniuUploadUtils.getInstance().uploadMutliFiles(list, new QiniuUploadUtils.UploadMutliListener() {
                        @Override
                        public void onUploadMutliSuccess(List<String> keyList) {
                            String image = "";
                            for(String s :keyList){
                                image = image+"|"+(yuming+s);
                                Log.i("image",""+image);
                            }
                            Map<String,String> map = new HashMap<>();
                            map.put("content",ed.getText().toString().trim());
                            map.put("image",image);
                            post("personal/feedback",map,BaseBean.class,true);
                        }
                        @Override
                        public void onUploadMutliFail(Error error) {
                            toast("上传图片失败");
                        }
                    },SPUtils.getInstance(getActivity()).getString("uptoken"));
                }else {
                    Map<String,String> map = new HashMap<>();
                    map.put("content",ed.getText().toString().trim());
                    map.put("image","");
                    post("personal/feedback",map,BaseBean.class,true);
                }
                break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("onActivityResult--->","resultCode--->"+resultCode);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //包括裁剪和压缩后的缓存，要在上传成功后调用，注意：需要系统sd卡权限
//                    PictureFileUtils.deleteCacheDirFile(MainActivity.this);
                    //postMultiPhoto(selectList);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }

    }
}
